package com.bob.clan.wxconnector.controller;

import java.io.*;
import com.bob.clan.wxconnector.component.MpComponent;
import com.bob.clan.wxconnector.component.WxMsgComponent;
import com.bob.clan.wxconnector.DTO.WxMsgDTO;
import com.bob.clan.wxconnector.entity.Mp;
import com.bob.clan.wxconnector.entity.WxMsg;
import com.bob.clan.wxconnector.service.IWxMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Arrays;

@Slf4j
@Controller
public class MonitorController {
    @Autowired
    private WxMsgComponent wxMsgComponent;
    @Autowired
    private IWxMsgService wxMsgService;
    @Autowired
    private MpComponent mpComponent;

    @GetMapping(value = "/wechat/monitor/{sysCode}")
    public void verifyConnect(@PathVariable String sysCode, String signature, String timestamp, String nonce, String echostr, HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.debug("有微信服务器开始请求认证了/wechat/monitor======signature:" + signature + ",timestamp:" + timestamp + ",nonce:" + nonce + ",echostr:" + echostr);
        Mp mp = mpComponent.getBySysCode(sysCode);
        String checkToken = mp.getCheckToken();
        String cur_signature = getSignature(checkToken, timestamp, nonce);
        if (signature.equals(cur_signature)) {
            response.getWriter().print(echostr);
        } else {
            log.warn("monitor的入口遭到非法连接，已被拒!");
        }
    }



    /**
     * 接收微信服务器的消息与事件的推送，并做出回应
     *
     * @param request
     * @param response
     * @return
     * @throws java.io.IOException
     */
    @PostMapping(value = "/wechat/monitor/{sysCode}")
    public void onMsgOrEvent(@PathVariable String sysCode, HttpServletRequest request, HttpServletResponse response) throws IOException, JAXBException, IllegalAccessException {
        //将微信服务器传来的封装在request里的消息，保存至库；
        String wxMsgStr = getXmlStr(request);
        log.info(sysCode+",收到事件："+wxMsgStr);
        WxMsgDTO wxMsgDTO = wxMsgComponent.xml2Msg(wxMsgStr, WxMsgDTO.class);

        WxMsg wxMsg = wxMsgComponent.dto2Msg(wxMsgDTO);
        wxMsgService.save(wxMsg);

        //为相关事做提代响应；
        String respMessage = monitorRespMessage(wxMsg);
        PrintWriter out = response.getWriter();
        out.print(respMessage);
        out.close();
    }


    /**
     * 按微信平台要求建的证规则
     * @param token
     * @param timestamp
     * @param nonce
     * @returnt 签名，用于匹配微信服务器发送的signature是否一致；
     */
    private String getSignature(String token, String timestamp, String nonce) {
        try {
            String[] array = new String[] { token, timestamp, nonce };
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < 3; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
    private String getXmlStr(HttpServletRequest request) throws IOException {
        InputStream inputStream = request.getInputStream();
        // 使用BufferedReader读取输入流中的数据
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append(System.lineSeparator()); // 添加换行符以保留原始格式（可选）
            }
        }
        // 获取完整的XML字符串
        String xmlString = stringBuilder.toString().trim(); // 去除末尾的换行符
        return xmlString;
    }

    private String monitorRespMessage(WxMsg wxMsg) {
        return "";
    }

    @RequestMapping("/authorizeLogin")
    public void authorizeLogin() {
        System.out.println("=============authorizeLogin successful!=================");

    }
}
